package spring.di.demo;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 文章地址：https://mp.weixin.qq.com/s/rMfncd1-P510OZFcZpDq3A
 * @author wzg
 * @date 2021/6/23 13:50
 */
public class Container {
    private static final  Map<String,Object> instanceMap =new HashMap<String, Object>(2);
    private static int count=0;
    public static void main(String[] args) throws Exception{
        Class[] classes={A.class,B.class};
        for(Class clazz:classes){
            getBean(clazz);
        }
        System.out.println("end");
    }

    /**
     * 获取 bean 同时属性依赖注入
     * 支持循环依赖
     * @param type
     * @return
     */
    private static <T> T getBean(Class<T> type) throws Exception{
        System.out.println("Invoke count:"+(count++));
        String beanName=type.getSimpleName().toLowerCase();
        if(instanceMap.containsKey(beanName)){
            return (T)instanceMap.get(beanName);
        }
        Object object=type.getDeclaredConstructor().newInstance();

        instanceMap.put(beanName,object);
        Field[] fields=object.getClass().getDeclaredFields();
        Field[] temp=type.getFields();
        if(fields!=null && fields.length>0){
            for (Field field:fields) {
                Class<?> fieldClass=field.getType();
                String fieldClassName=fieldClass.getSimpleName().toLowerCase();
                field.setAccessible(true);
                field.set(object,instanceMap.containsKey(fieldClassName)?instanceMap.get(fieldClassName):getBean(fieldClass));
            }
        }

        return (T) object;
    }
}
